package com.qf.listener;


import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


@Component
public class RabbitListeners {
    private StringRedisTemplate redisTemplate;

    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @RabbitListener(queues = "wangzong")
    public void onMessage(String msg, Channel channel, Message message) throws IOException {

        System.out.println(msg);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        System.out.println(deliveryTag);

//        防止重复消费
//        获取到消息的ID
        String messageid =message.getMessageProperties().getHeader("spring_listener_return_correlation");
        System.err.println("id======>"+messageid);
        //保存到 redis 设置1 分钟有效期,返回 true 代表设置成功,也就是意味着里面没有数据
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(messageid, "0", 1, TimeUnit.MINUTES);
        if(aBoolean){
            System.out.println(msg);
            redisTemplate.opsForValue().set(messageid, "1");
            channel.basicAck(deliveryTag, false);
        }else {
            //reids 中有这个数据了,但是数据有可能并不是一个完成状态,有可能是 0
            String s = redisTemplate.opsForValue().get(messageid);
            if("1".equals(s)){
//            消息实际是已经被消费了
                channel.basicAck(deliveryTag, false);
            }
        }
    }
}
